package com.wgj.android.http.weixin;

import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.XNetworkUtils;
import com.jiaai.xui.utils.http.BaseHttpCallBack;
import com.wgj.android.http.weixin.model.SyncKey;
import com.wgj.android.http.weixin.model.WXInfo;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/11/25.
 */

public class WXHttp {
    private static WXHttp wxHttp;
    private  OkHttpClient client = null;
    private static  String[] excaues=new String[]{"jslogin", "login?loginicon"};
    public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");


    public static WXHttp obtain(){
        if (wxHttp == null) {
            wxHttp = new WXHttp();
        }
        return wxHttp;
    }
    private   WXHttp(){
        client= new OkHttpClient().newBuilder()
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new WeiXingLoginInterceptor())
                .build();
    }
    /**
     * 同步请求GET
     * @param url
     * @param params
     * @return
     */
    public String syncGet(String url, Map<String, Object> params)throws Exception{
        Request.Builder builder = new Request.Builder();

        Request request = builder.url(url.concat(getUrlParamsByMap(params))).build();

        try {
            Response response = client.newCall(request).execute();
            Headers headers= response.headers();
            if(headers.names().contains("Set-Cookie")){
                StringBuilder sb = new StringBuilder();
                for (String e : headers.values("Set-Cookie")){
                    sb.append(e).append(";");
                }
                WeiXinCacheUtil.saveCookie(sb.toString());
            }


            return response.body().string();
        } catch (Exception e) {
           throw  e;
        }
    }

    /**
     * 同步请求POST
     * @param url
     * @param json
     * @return
     */
    public String syncPost(String url, String json)throws Exception{
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request.Builder obj = new Request.Builder()
                .url(url);
        obj.post(requestBody);
        Request request = obj.build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 获取二进制
     * @param url
     * @param params
     * @param callBack
     */
    public void bytePost(String url, Map<String, Object> params, final BaseHttpCallBack callBack){
        Request request =new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callBack.onSuccess(response);
            }
        });
    }




    public void get(String url, Map<String, Object> params,  final WXHttpCallback callBack) {
        Request request =new Request.Builder().url(url + getUrlParamsByMap(params)).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if(XNetworkUtils.isAvailable()){
                    callBack.onFailed(false);
                }else{
                    callBack.onFailed(true);
                }
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                if (response.request().url().toString().contentEquals("webwxnewloginpage")){
                    WeiXinCacheUtil.saveCookie(null);
                    Headers headers= response.headers();
                    if(headers.names().contains("Set-Cookie")){
                        StringBuilder sb = new StringBuilder();
                        for (String e : headers.values("Set-Cookie")){
                            sb.append(e).append(";");
                        }
                        WeiXinCacheUtil.saveCookie(sb.toString());
                    }

                }

                try {
                    callBack.onSuccess(response.body().string());
                } catch (IOException e) {
                    callBack.onFailed(false);
                }
            }
        });
    }

    public void post(String url, String json, final WXHttpCallback callback) {

        RequestBody requestBody = RequestBody.create(JSON, json);

        Request.Builder obj = new Request.Builder()
                .url(url);
        if (json != null) obj.post(requestBody);
        Request request = obj.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                callback.onFailed(false);

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                try {
                    callback.onSuccess(response.body().string());
                } catch (IOException e) {
                    callback.onFailed(false);
                }
            }
        });
    }



    private String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null||map.isEmpty()) {
            return "";
        }
        StringBuffer params = new StringBuffer("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.append(entry.getKey());
            params.append("=");
            params.append(entry.getValue());
            params.append("&");
        }
        String str=params.toString();
        return str.substring(0,str.length()-1);
    }


    public  interface  WXHttpCallback{
        void onSuccess(String body);
        void onFailed(boolean isNettWork);
    }



    public static   boolean checkIsLogin(){
        WXInfo info=WeiXinCacheUtil.getInfo();
        if(info==null ||  !info.isLogin()){

                return false;
        }else {
            return  info.isLogin();
        }
    }

    public  static SyncKey checkIsSync(){
        SyncKey syncKey = WeiXinCacheUtil.getSynckey();
        if (syncKey != null){
            return syncKey;
        }
        return null;
    }

    class WeiXingLoginInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            for (String s:excaues){
                if(request.url().toString().indexOf(s)>0){
                    return  chain.proceed(request);
                }
            }

            WXInfo info=WeiXinCacheUtil.getInfo();
            if(info!=null){
                Request.Builder builder = request.newBuilder().removeHeader("User-Agent").addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
                String url=request.url().toString();
                builder.url(url);
                builder.addHeader("Host", info.getBaseUrl());
                builder.addHeader("Origin", "https://"+info.getBaseUrl());
                builder.addHeader("Referer", "https://wx2.qq.com/");
                builder.addHeader("Content-Type", "application/json");

                String cookie=WeiXinCacheUtil.getCookie();
                if(!XEmptyUtils.isSpace(cookie)){
                    builder.addHeader("Cookie", cookie);
                }
                return  chain.proceed(builder.build());
            }else {
                return  chain.proceed(request);
            }
        }
    }




}
